<template>
  <div class="container">
    <i
      class="el-icon-circle-close"
      @click="handleRemove(imageUrlNew)"
      style="cursor: pointer"
    ></i>

<!--
    :http-request="getFile"
 -->
    <el-upload
      :headers='headers'
      action="https://jsonplaceholder.typicode.com/posts/"
      ref="upLoad"
      :show-file-list="false"
      list-type="picture-card"
    >
      <img v-if="imageUrlNew" :src="imageUrlNew" class="avatar" />
      <div v-if="!imageUrlNew" class="text">上传图片</div>
      <!-- <div slot="file" slot-scope="{ file }">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions"> </span>
      </div> -->
    </el-upload>
  </div>
</template>

<script>
// import cos and init
import COS from 'cos-js-sdk-v5'

// 配置请求头,解决跨域问题
import { getToken } from '@/utils/auth'

const cos = new COS({
  SecretId: 'AKIDBBwQfdKkvrZ2E9oBIAl6AyVljRu74k9H',
  SecretKey: 'sUrxmJZZIkwtZ0B5j5B0Zrsc5IFwNXKq'
})
export default {
  name: 'UpLoadImg',
  props: {
    imageUrl: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      imageUrlNew: ''

    }
  },

  watch: {
    imageUrlNew: function () {
      this.imageUrl = this.imageUrlNew
    }
  },

  created () {
    this.showImage()
  },

  computed: {
    headers () {
      const token = getToken()
      return {
        Authorization: `Bearer ${token}`
      }
    }
  },

  methods: {
    // 图片数据回显
    showImage () {
      if (this.imageUrl) {
        this.imageUrlNew = this.imageUrl
      }
    },

    handleRemove (file) {
      this.imageUrlNew = ''
    },

    getFile (param) {
      // 会出现跨域问题

      cos
        .putObject({
          Bucket: 'liu-1307084383' /* 存储桶名字 */,
          Region: 'ap-nanjing' /* 存储桶所在地域 */,
          Key: param.file.name /* 文件名 */,
          StorageClass: 'STANDARD',
          Body: param.file, // 图片文件对象
          onProgress: function (progressData) {
            //   console.log(JSON.stringify(progressData))
          }
        })
        .then((res) => {
          //   upload success :insert url to editor
          this.imageUrlNew = `https:${res.Location}`
          this.$emit('update:imageUrl', this.imageUrlNew)
        })
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  position: relative;

  display: inline-block;
}

.el-icon-circle-close {
  position: absolute;
  top: -10px;
  right: -10px;
}

::v-deep .el-upload--picture-card {
  width: 100px;
  height: 60px;
}

.text {
  position: absolute;
  width: 100px;
  line-height: 60px;
  left: 50%;
  top: 50%;
  margin-top: -30px; /* 高度的一半 */
  margin-left: -50px; /* 宽度的一半 */
  font-size: small;
}

i {
  font-size: 20px;
}

// show image container
.avatar {
  position: absolute;
  width: 100px;
  height: 60px;
  margin-left: -50px; /* 宽度的一半 */
}
</style>
